import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { ApiResponse, PaginatedResponse } from '@weubi/shared';
import { useAuthStore } from '../stores/authStore';
import toast from 'react-hot-toast';

// 创建 axios 实例
const createApiClient = (): AxiosInstance => {
  const client = axios.create({
    baseURL: import.meta.env.VITE_API_URL || '/api',
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json',
    },
  });

  // 请求拦截器 - 添加认证令牌
  client.interceptors.request.use(
    (config) => {
      const { tokens } = useAuthStore.getState();
      if (tokens?.accessToken) {
        config.headers.Authorization = `Bearer ${tokens.accessToken}`;
      }
      return config;
    },
    (error) => Promise.reject(error)
  );

  // 响应拦截器 - 处理错误和令牌刷新
  client.interceptors.response.use(
    (response) => response,
    async (error) => {
      const originalRequest = error.config;

      // 处理 401 错误（令牌过期）
      if (error.response?.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;

        try {
          await useAuthStore.getState().refreshToken();
          
          // 重新发送原始请求
          const { tokens } = useAuthStore.getState();
          if (tokens?.accessToken) {
            originalRequest.headers.Authorization = `Bearer ${tokens.accessToken}`;
          }
          
          return client(originalRequest);
        } catch (refreshError) {
          // 刷新失败，跳转到登录页
          useAuthStore.getState().logout();
          window.location.href = '/login';
          return Promise.reject(refreshError);
        }
      }

      // 显示错误提示
      if (error.response?.data?.message) {
        toast.error(error.response.data.message);
      } else if (error.message) {
        toast.error(error.message);
      }

      return Promise.reject(error);
    }
  );

  return client;
};

const apiClient = createApiClient();

// 认证 API
export const authApi = {
  login: (data: { email: string; password: string }) =>
    apiClient.post<ApiResponse<{ user: any; tokens: any }>>('/auth/login', data),
  
  logout: () =>
    apiClient.post<ApiResponse>('/auth/logout'),
  
  refreshToken: (refreshToken: string) =>
    apiClient.post<ApiResponse<{ user: any; tokens: any }>>('/auth/refresh', { refreshToken }),
  
  verifyToken: () =>
    apiClient.get<ApiResponse<{ user: any }>>('/auth/verify'),
  
  updateProfile: (data: any) =>
    apiClient.put<ApiResponse<any>>('/auth/me', data),
  
  changePassword: (data: { currentPassword: string; newPassword: string }) =>
    apiClient.post<ApiResponse>('/auth/change-password', data),
};

// 任务 API
export const tasksApi = {
  getTasks: (params?: any) =>
    apiClient.get<PaginatedResponse<any>>('/tasks', { params }),
  
  getTask: (id: string) =>
    apiClient.get<ApiResponse<any>>(`/tasks/${id}`),
  
  createTask: (data: any) =>
    apiClient.post<ApiResponse<any>>('/tasks', data),
  
  updateTask: (id: string, data: any) =>
    apiClient.put<ApiResponse<any>>(`/tasks/${id}`, data),
  
  deleteTask: (id: string) =>
    apiClient.delete<ApiResponse>(`/tasks/${id}`),
  
  runTask: (id: string) =>
    apiClient.post<ApiResponse<any>>(`/tasks/${id}/run`),
  
  pauseTask: (id: string) =>
    apiClient.post<ApiResponse<any>>(`/tasks/${id}/pause`),
  
  resumeTask: (id: string) =>
    apiClient.post<ApiResponse<any>>(`/tasks/${id}/resume`),
  
  cancelTask: (id: string) =>
    apiClient.post<ApiResponse<any>>(`/tasks/${id}/cancel`),
  
  getTaskStats: () =>
    apiClient.get<ApiResponse<any>>('/tasks/stats/overview'),
};

// 数据 API
export const dataApi = {
  getData: (params?: any) =>
    apiClient.get<PaginatedResponse<any>>('/data', { params }),
  
  getDataItem: (id: string) =>
    apiClient.get<ApiResponse<any>>(`/data/${id}`),
  
  deleteData: (id: string) =>
    apiClient.delete<ApiResponse>(`/data/${id}`),
  
  bulkDeleteData: (ids: string[]) =>
    apiClient.delete<ApiResponse<{ deletedCount: number }>>('/data', { data: { ids } }),
  
  markAsProcessed: (id: string) =>
    apiClient.post<ApiResponse<any>>(`/data/${id}/processed`),
  
  markAsInvalid: (id: string, reason?: string) =>
    apiClient.post<ApiResponse<any>>(`/data/${id}/invalid`, { reason }),
  
  exportData: (params?: any) =>
    apiClient.get('/data/export/download', { 
      params, 
      responseType: 'blob',
    }),
  
  getDataStats: () =>
    apiClient.get<ApiResponse<any>>('/data/stats/overview'),
  
  getTaskDataStats: (taskId: string) =>
    apiClient.get<ApiResponse<any>>(`/data/stats/by-task/${taskId}`),
  
  deduplicateData: (data: { taskId?: string; dryRun?: boolean }) =>
    apiClient.post<ApiResponse<any>>('/data/deduplicate', data),
};

// 健康检查 API
export const healthApi = {
  getHealth: () =>
    apiClient.get<any>('/health'),
  
  getDetailedHealth: () =>
    apiClient.get<any>('/health/detailed'),
};

export default apiClient;
